import React, { Component,createRef } from 'react'

export default class TodoItem extends Component {
    constructor(){
        super()
        this.state = {
            isEdit:false  //控制当前组件的编辑状态
        }
        this.editInput = createRef()
    }
    handleEdit = (bool)=>{
        this.setState({ //setState是异步的
            isEdit:bool
        },()=>{  //此处的回调函数，会等本次数据引发的视图更新完毕后再执行
            this.editInput.current.focus() 
            if(!bool){ 
                let {objectId,handleUpdate} = this.props
                let v = this.editInput.current.value
                // console.log(v);
                handleUpdate(objectId,v)  //触发父级组件，更新任务名称
            }
        })
        // this.editInput.current.focus()  //执行这句代码的时候，输入框的DOM元素还没有生成
    }
    render() {
        let {taskname,ischeck,objectId,idx} = this.props
        let {handleCheck,handleDel} = this.props
        let complete = ischeck?'completed':'' //完成状态
        let edit = this.state.isEdit?'editing':'' //编辑状态
        return (
            <li className={`${complete} ${edit}`}>
              <div className="view">
                <input 
                    type="checkbox" 
                    className="toggle" 
                    checked={ischeck}
                    onChange={()=>{handleCheck(objectId)}}
                />
                <label onDoubleClick={()=>{this.handleEdit(true)}}>{taskname}</label>
                <button onClick={()=>{handleDel(objectId)}} className="destroy"></button>
              </div>
              <input 
                ref={this.editInput} 
                type="text" 
                className="edit" 
                defaultValue={taskname}
                onBlur={()=>{this.handleEdit(false)}}
              />
            </li>
        )
    }
}
